package com.dlwx.parttimetalent.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.adapter.MyAdapter;
import com.dlwx.parttimetalent.baidu.BaiduListener;
import com.dlwx.parttimetalent.baidu.LocationService;
import com.dlwx.parttimetalent.base.BaseActivity;
import com.dlwx.parttimetalent.base.MyApplication;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.initialsort.CharacterParser;
import com.dlwx.parttimetalent.initialsort.PinyinComparator;
import com.dlwx.parttimetalent.initialsort.SideBar;
import com.dlwx.parttimetalent.initialsort.SortAdapter;
import com.dlwx.parttimetalent.initialsort.SortModel;
import com.dlwx.parttimetalent.inter.LocationInter;
import com.dlwx.parttimetalent.utils.CityJson;
import com.dlwx.parttimetalent.utils.SPUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CityListActivity extends BaseActivity {

    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.lv_list)
    ListView lvList;
    @BindView(R.id.dialog)
    TextView dialog;
    @BindView(R.id.sidrbar)
    SideBar sidrbar;
    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    private SortAdapter adapter;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<SortModel> SourceDateList;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private List<SortModel> mSortList;
    /**
     * 热门城市
     */
    private String[] hotCitys = {
            "北京", "成都", "重庆", "广州", "杭州", "南京", "上海", "深圳", "天津", "武汉", "西安", "郑州", "兰州"
    };
    private CityJson.SanJiLianDBean sanJiLianDBean;
    private BaiduListener mListener;
    private LocationService locationService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_list);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initView() {
        tvMiddleTitle.setVisibility(View.VISIBLE);
        tvMiddleTitle.setText("定位");
        titleLeftOneBtn.setVisibility(View.VISIBLE);
    }


    private void initData() {
//        initTabBar(toolBar);
//        tvTitle.setText(R.string.location);
        sanJiLianDBean = MyApplication.sanJiLianDBean;
        List<CityJson.SanJiLianDBean.CityList> citylist = sanJiLianDBean.getCitylist();
        sidrbar.setTextView(dialog);
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();

        pinyinComparator = new PinyinComparator();
        String city= (String) SPUtils.get(this,Constant.CITY,"");
        tvCity.setText(city);
        View view = LayoutInflater.from(ctx).inflate(R.layout.item_pro_head, null);
        lvList.addHeaderView(view);
        GridView gv_list = (GridView) view.findViewById(R.id.gv_list);
        MyAdapter hotadapter = new MyAdapter(ctx, hotCitys);
        gv_list.setAdapter(hotadapter);

        SourceDateList = filledData(citylist);
//        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        adapter = new SortAdapter(this, SourceDateList);
        lvList.setAdapter(adapter);
        gv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                successBack(hotCitys[position]);
            }
        });
        tvCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                successBack(tvCity.getText().toString());
            }
        });
    }

    private void successBack(String hotCity1) {
        String hotCity = hotCity1;
        if(hotCity.endsWith("市")){
            hotCity= hotCity.substring(0,hotCity.length()-1);
        }
        Intent intent = new Intent();
        intent.putExtra("city", hotCity);
        setResult(Constant.CITY_RESULT, intent);
        finish();
    }


    private void initListener() {
        //设置右侧触摸监听
        sidrbar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    lvList.setSelection(position);
                }

            }
        });
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SortModel sortModel = mSortList.get(position - 1);

                successBack(sortModel.getName());
            }
        });
    }


    /**
     * 为ListView填充数据
     *
     * @param
     * @return
     */
    private List<SortModel> filledData(List<CityJson.SanJiLianDBean.CityList> citylist) {
        mSortList = new ArrayList<SortModel>();
        for (int i = 0; i < citylist.size(); i++) {
            List<CityJson.SanJiLianDBean.CityList.CBean> c = citylist.get(i).getC();
            for (int j = 0; j < c.size(); j++) {
                SortModel sortModel = new SortModel();
                sortModel.setName(c.get(j).getN());
                sortModel.setPro(citylist.get(i).getP());
                //汉字转换成拼音
                String pinyin = characterParser.getSelling(c.get(j).getN());
                String sortString = pinyin.substring(0, 1).toUpperCase();

                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    sortModel.setSortLetters(sortString.toUpperCase());
                } else {
                    sortModel.setSortLetters("#");
                }

                mSortList.add(sortModel);

            }
        }
        return mSortList;

    }


    @OnClick(R.id.title_left_one_btn)
    public void onViewClicked() {
        this.finish();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mListener=new BaiduListener(this, new LocationInter() {
            @Override
            public void getAddressInfo(BDLocation location) {
                String city=location.getCity();
                if(city.endsWith("市")){
                    city= city.substring(0,city.length()-1);
                }
                tvCity.setText(city);
            }
        });
//        locationService = ((MyApplication) getApplication()).locationService;
//        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
//        locationService.registerListener(mListener);
//        //注册监听
//        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
//        locationService.start();// 定位SDK
    }

    @Override
    protected void onStop() {
        super.onStop();
//        locationService.unregisterListener(mListener); //注销掉监听
//        locationService.stop(); //停止定位服务
    }
}
